/*
 * @Author: sonss
 * @Date: 2023-06-28 19:50:48
 * @LastEditTime: 2024-08-22 13:08:23
 * @FilePath: /ss-file-antd/src/pages/Account/Setup/index.tsx
 * @Description: 修改密码
 */

import { EditPwd } from '@/services/account';
import {
  PageContainer,
  ProCard,
  ProForm,
  ProFormGroup,
  ProFormInstance,
  ProFormText,
} from '@ant-design/pro-components';
import { message } from 'antd';
import React, { useRef } from 'react';

const AccountSetupIndexPage: React.FC = () => {
  const formRef = useRef<ProFormInstance>();
  const [msgApi, contextHolder] = message.useMessage();

  const finish = async (values: ACCOUNT.EditPwdForm) => {
    const res = await EditPwd(values);
    if (res.code !== 0) {
      msgApi.error(res.message || '未知错误');
      return;
    }

    msgApi.success('恭喜您，操作已成功！');
    formRef.current?.resetFields();
  };

  return (
    <>
      <PageContainer title="账号设置" content="在此处可以修改您的账号密码了">
        <ProCard>
          <ProForm<ACCOUNT.EditPwdForm> formRef={formRef} onFinish={finish}>
            <ProFormGroup>
              <ProFormText.Password
                width="md"
                name="oldPwd"
                label="旧密码"
                rules={[
                  { required: true, message: '请输入旧密码' },
                  { type: 'string', min: 4, max: 20, message: '旧密码错误' },
                ]}
              />
            </ProFormGroup>
            <ProFormGroup>
              <ProFormText.Password
                width="md"
                name="newPwd"
                label="新密码"
                rules={[
                  { required: true, message: '请输入新密码' },
                  { type: 'string', min: 4, max: 20, message: '密码长度只能为4-20位字符' },
                ]}
              />
            </ProFormGroup>
            <ProFormGroup>
              <ProFormText.Password
                width="md"
                name="cfmPwd"
                label="确认新密码"
                rules={[
                  { required: true, message: '请输入确认新密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('newPwd') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('确认新密码不一致'));
                    },
                  }),
                ]}
              />
            </ProFormGroup>
          </ProForm>
        </ProCard>
      </PageContainer>
      {contextHolder}
    </>
  );
};

export default AccountSetupIndexPage;
